package com.mall.app.utils;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.mall.app.bean.TbUser;
import com.mall.app.service.TbBuyerService;
import com.mall.app.service.TbUserService;

public class MyRealm extends AuthorizingRealm{
/**
 * 定义用户认证或者授权的类
 *
 */
	@Autowired
	private TbUserService userService;
	
	@Autowired
	private TbBuyerService buyerService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 * 处理用户登录
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String)token.getPrincipal();
		
		MyToken mytoken=(MyToken)token;
		
		//将登录后的信息封装进去，返回去匹配密码
		SimpleAuthenticationInfo info=null;
		MyAccount account = null;
		
		switch(mytoken.getUsertype()){
		case "User":
			account=login(username);
			if(account!=null){
				//如果能查到此用户
				//其中getName()方法是获取当前认证类的名称
				SecurityUtils.getSubject().getSession().setAttribute("account", account);
				info=new SimpleAuthenticationInfo(account.getUsername(),account.getPassword(),getName());
				
			}
			
			break;
			
		case "Buyer":
			account = buyerService.login(username);
			if(account!=null){
				//如果能查到此用户
				//其中getName()方法是获取当前认证类的名称
				SecurityUtils.getSubject().getSession().setAttribute("account", account);
				info=new SimpleAuthenticationInfo(account.getUsername(),account.getPassword(),getName());
				
			}
			break;
		}
		
		return info;
	}
	/**
	 * 处理用户权限
	 * 调用业务层去查数据库
	 * @param username
	 * @return
	 */
	private TbUser login(String username){
		return userService.login(username);
	}
}
